package com.dong.c10_netty_chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2021-03-09 14:50
 */
public class GroupChatClient {
    private final String host;
    private final int port;

    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;

    }
    public void run() {
        NioEventLoopGroup workerGroup = null;
        try {
            Bootstrap bootstrap = new Bootstrap();
            workerGroup = new NioEventLoopGroup(8);
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(new GroupChatClientHandler());
                        }
                    })
            ;
            ChannelFuture channelFuture = bootstrap.connect(this.host, this.port).sync();

            Channel channel = channelFuture.channel();
            System.out.println("我已经准备好了"+ channel.localAddress());

            Scanner scanner = new Scanner(System.in);
            System.out.println("客户端可以进行输入了...");
            while(scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                System.out.println("客户端输出消息: "+msg);
                channel.writeAndFlush(msg);
            }
            channel.closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        GroupChatClient groupChatClient = new GroupChatClient("127.0.0.1", 7000);
        groupChatClient.run();
    }
}
